//
//  EditMaterialVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/28.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SVProgressHUD
import SCLAlertView
protocol EditMaterialDelegate: class {
    func didEditMaterial(with material: MaterialDetail)
}

class EditMaterialVC: UITableViewController {
    
    var materialDetail: MaterialDetail!
    var editMaterial = EditMaterial()
    let imagePickerVC = UIImagePickerController()
    var listsTitle = [["名称", "种类", "货号", "单价", "单位"], [""], [""], [""], [""], [""]]
    var keyBoardTypes: [UIKeyboardType?] = [.default, nil, .numberPad, .numberPad, .default]
    let sectionTitles = [nil, "自定义录入项", "色板图片", "成分", "详情图片", "商品相关图"]
    var placeHolder = ["请输入面料名称", nil,  "请输入货号", "请输入单价", "请输入单位"]
    let helper = MaterialHelper()
    var topStyle: MaterialStyle!
    var nextStyle: MaterialStyle!
    var selectedRow: IndexPath!
    var materialImage: UIImage!
    var image: UIImage!
    weak var delegate: EditMaterialDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        editMaterial.materialId = materialDetail.id
        print(materialDetail)
        tableView.keyboardDismissMode = .onDrag
        tableView.rowHeight = 60
        tableView.register(UINib(nibName: "TextCell", bundle: nil), forCellReuseIdentifier: "TextCell")
        tableView.register(UINib(nibName: "ChooseCell", bundle: nil), forCellReuseIdentifier: "ChooseCell")
        tableView.register(UINib(nibName: "AddLineCell", bundle: nil), forCellReuseIdentifier: "AddLineCell")
        tableView.register(UINib(nibName: "ColorCell", bundle: nil), forCellReuseIdentifier: "ColorCell")
        tableView.register(UINib(nibName: "ComponentCell", bundle: nil), forCellReuseIdentifier: "ComponentCell")
        tableView.register(UINib(nibName: "OneImageCell", bundle: nil), forCellReuseIdentifier: "OneImageCell")
        tableView.register(UINib(nibName: "ImageCell", bundle: nil), forCellReuseIdentifier: "ImageCell")

        let cancel = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(cancelButtonTapped(_:)))
        let doneBt = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(doneButtonTapped(_:)))
        navigationItem.setLeftBarButton(cancel, animated: true)
        navigationItem.setRightBarButton(doneBt, animated: true)
    }
    @objc func cancelButtonTapped(_ button: UIBarButtonItem!) {
        self.dismiss(animated: true, completion: nil)
    }
    @objc func doneButtonTapped(_ button: UIBarButtonItem!) {
        print(editMaterial)
        debugPrint("------------")
        print(materialDetail)
        guard materialDetail.attr != "", materialDetail.color.count > 0, materialDetail.name != "", materialDetail.no != "", materialDetail.price != "", materialDetail.unit != "", materialDetail.picture.count > 0 else {
            showError(message: "请填写必要信息")
            return
        }
        let colorLists = editMaterial.color
        let picture = editMaterial.picture
        SVProgressHUD.show()
        view.isUserInteractionEnabled = false
        let createPictureGroup = DispatchGroup()
        let _ = DispatchQueue.global(qos: .utility)
        var networkError: RequestError?
        
        // Color创建图片
        DispatchQueue.concurrentPerform(iterations: colorLists.count) { (i) in
            let index = Int(i)
            if colorLists[index].type != 3 {
                return
            }
            createPictureGroup.enter()
            helper.createPicture(base64code: colorLists[index].picture, completeHandler: { (error, url) in
                guard error == nil else {
                    networkError = error
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    self.view.isUserInteractionEnabled = true
                    createPictureGroup.leave()
                    return
                }
                self.editMaterial.color[i].picture = url!
                createPictureGroup.leave()
            })
        }
        // 如果修改了产品相关图片
        if materialImage != nil {
            createPictureGroup.enter()
            let materialBase64Image = convertToBase64(materialImage)!
            helper.createPicture(base64code: materialBase64Image) { (error, url) in
                guard error == nil else {
                    networkError = error
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    createPictureGroup.leave()
                    return
                }
                self.editMaterial.body = url!
                createPictureGroup.leave()
            }
        }
        
        // 产品详情图片
        DispatchQueue.concurrentPerform(iterations: picture.count) { (i) in
            let index = Int(i)
            if picture[index].type != 3 {
                return
            }
            createPictureGroup.enter()
            helper.createPicture(base64code: picture[index].img, completeHandler: { (error, url) in
                guard error == nil else {
                    networkError = error
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    self.view.isUserInteractionEnabled = true
                    createPictureGroup.leave()
                    return
                }
                self.editMaterial.picture[index].img = url!
                createPictureGroup.leave()
            })
        }
        createPictureGroup.notify(queue: .main) {
            guard networkError == nil else {
                SVProgressHUD.showError(withStatus: "error")
                return
            }
            let jsonEncoder = JSONEncoder()
            let data = try! jsonEncoder.encode(self.editMaterial)
            self.helper.editMaterial(data: data, completeHandler: { (error) in
                guard error == nil else {
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    SVProgressHUD.dismiss(withDelay: 1.5)
                    self.dismiss(animated: true, completion: nil)
                    return
                }
                self.delegate?.didEditMaterial(with: self.materialDetail)
                SVProgressHUD.showSuccess(withStatus: "成功")
                SVProgressHUD.dismiss(withDelay: 1.5)
                self.dismiss(animated: true, completion: nil)
            })
        }
        
    }
    @objc func cellLeftBtTapped(_ button: UIButton!) {
        SVProgressHUD.show()
        helper.getTopStyles { [weak self] (error, styles) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                return
            }
            
            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
            for i in 0 ..< styles!.count {
                alertVC.addAlert(styles![i].name, action: { [weak self] (_) in
                    self?.topStyle = styles![i]
                    button.setTitle("\(styles![i].name)", for: .normal)
                })
            }
            self?.present(alertVC, animated: true, completion: nil)
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
    
    @objc func cellRightBtTapped(_ button: UIButton!) {
        guard topStyle != nil else {
            self.showError(message: "请先修改一级品类！")
            return
        }
        SVProgressHUD.show()
        helper.getNextStyles(from: topStyle.id) { [weak self] (error, styles) in
            guard let styles = styles else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                return
            }
            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
            for i in 0 ..< styles.count {
                alertVC.addAlert(styles[i].name, action: { [weak self] (_) in
                    self?.nextStyle = styles[i]
                    button.setTitle("\(styles[i].name)", for: .normal)
                })
            }
            self?.present(alertVC, animated: true, completion: nil)
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return listsTitle.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 5
        } else if section == 1 {
            if let userDefines = materialDetail.userDefine {
                return userDefines.count + 1
            } else {
                materialDetail.userDefine = []
                return 1
            }
        } else {
            return 1
        }
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 1 && indexPath.row != 0 {
            return true
        } else {
            return false
        }
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if materialDetail.userDefine![indexPath.row-1].id == nil {
                var addUserDefines = [Int]()
                for i in 0 ..< editMaterial.userDefine.count {
                    if editMaterial.userDefine[i].type == 3 {
                        addUserDefines.append(i)
                    }
                }
                let count = tableView.numberOfRows(inSection: indexPath.section)
                print("count \(count)")
                let index = count - indexPath.row
                print("index\(index)")
                print(editMaterial.userDefine)
                editMaterial.userDefine.remove(at: addUserDefines[addUserDefines.count-index])
                materialDetail.userDefine!.remove(at: indexPath.row-1)
            } else {
                let userDefine = CodableUserDefine(type: 1, id: materialDetail.userDefine![indexPath.row-1].id)
                editMaterial.userDefine.append(userDefine)
                materialDetail.userDefine!.remove(at: indexPath.row-1)
            }
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let section = indexPath.section
        let row = indexPath.row
        if indexPath.section == 0 {
            if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ChooseCell") as! ChooseCell
                var a = materialDetail.attr.split(separator: "-")
                cell.leftButton.setTitle(String(a[1]), for: .normal)
                cell.rightButton.setTitle(String(a[0]), for: .normal)
                cell.leftButton.addTarget(self, action: #selector(cellLeftBtTapped(_:)), for: .touchUpInside)
                cell.rightButton.addTarget(self, action: #selector(cellRightBtTapped(_:)), for: .touchUpInside)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
                var details = [materialDetail.name, nil, materialDetail.no, materialDetail.price, materialDetail.unit]
                cell.titleLabel.text = listsTitle[0][indexPath.row]
                cell.textField.text = details[row]
                cell.textField.placeholder = placeHolder[row]
                cell.textField.keyboardType = keyBoardTypes[row]!
                cell.textField.delegate = self
                return cell
            }
        } else if section == 1 {
            if row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "AddLineCell") as! AddLineCell
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
                cell.titleLabel.text = materialDetail.userDefine![row-1].key
                cell.textField.placeholder = "请输入相关信息"
                cell.textField.text = materialDetail.userDefine![row-1].value
                cell.textField.delegate = self
                
                return cell
            }
        } else if section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell") as! ColorCell
            cell.delegate = self
            var items = [ColorOfMaterial]()
            var images = [Any]()
            for color in materialDetail.color {
                images.append(color.picture)
                items.append(ColorOfMaterial(no: color.no, color: color.color, strock: color.stock))
            }
            cell.images = images
            cell.items = items
            cell.addButton.addTarget(self, action: #selector(sectionTwo(_:)), for: .touchUpInside)
            return cell
        } else if section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ComponentCell") as! ComponentCell
            cell.delegate = self
            cell.items = materialDetail.component
            print("-----")
            print(cell.items.count)
            return cell
        } else if section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "OneImageCell") as! OneImageCell
            if let url = URL(string: materialDetail.body) {
                cell.imgView.kf.setImage(with: url)
            } else if let image = materialImage {
                cell.imgView.image = image
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageCell
            cell.addButton.addTarget(self, action: #selector(sectionFive(_:)), for: .touchUpInside)
            cell.delegate = self
            var images = [String]()
            for item in materialDetail.picture {
                images.append(item.img)
            }
            cell.images = images
            return cell
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 || indexPath.section == 1 {
            return 50
        } else if indexPath.section == 4 {
            return 200
        }
        else {
            return 110
        }
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 && indexPath.row == 0 {
            let alerts = ["克重", "纱支", "手感", "产地", "下单制造周期"]
            let alertVC = UIAlertController(title: "新建条目", message: nil, preferredStyle: .alert)
            for i in 0 ..< alerts.count-1 {
                alertVC.addAlert(alerts[i], action: { [weak self] (_) in
                    self?.materialDetail.userDefine!.append(CodableUserDefine(key: alerts[i], value: ""))
                    self?.editMaterial.userDefine.append(CodableUserDefine(key: alerts[i], type: 3))
                    tableView.beginUpdates()
                    tableView.insertRows(at: [IndexPath(row: (self?.materialDetail.userDefine!.count)!, section: indexPath.section)], with: .automatic)
                    tableView.endUpdates()
                })
            }
            let customAlert = UIAlertAction(title: "自定义", style: .default, handler: { (_) in
                let TFAlertVC = UIAlertController(title: "自定义", message: nil, preferredStyle: .alert)
                TFAlertVC.addTextField(configurationHandler: { (textField) in
                    textField.placeholder = "请输入相关信息"
                })
                TFAlertVC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak TFAlertVC] (_) in
                    guard let text = TFAlertVC?.textFields![0].text else {
                        return
                    }
                    guard text != "" else { return }
                    self.materialDetail.userDefine!.append(CodableUserDefine(key: text, value: ""))
                    self.editMaterial.userDefine.append(CodableUserDefine(key: text, type: 3))
                    tableView.beginUpdates()
                    tableView.insertRows(at: [IndexPath(row: self.materialDetail.userDefine!.count, section: indexPath.section)], with: .automatic)
                    tableView.endUpdates()
                }))
                self.present(TFAlertVC, animated: true, completion: nil)
            })
            alertVC.addAction(customAlert)
            let cancelAlert = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertVC.addAction(cancelAlert)
            self.present(alertVC, animated: true, completion: nil)
        } else if indexPath.section == 4 && indexPath.row == 0 {
            selectedRow = indexPath
            presentImagePickerVC()
        }
    }
    
    // -MARK: section private methods
    /// show alert for different sections
    @objc //section 2 - 色板
    func sectionTwo(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        let indexPath = tableView.indexPathForRow(at: point)
        selectedRow = indexPath!
        presentImagePickerVC()
    }
    @objc func sectionFive(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        let indexPath = tableView.indexPathForRow(at: point)
        selectedRow = indexPath!
        presentImagePickerVC()
    }
    private func presentImagePickerVC() {
        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        imagePickerVC.allowsEditing = true
        imagePickerVC.delegate = self
        alertVC.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            self.imagePickerVC.sourceType = .camera
            self.present(self.imagePickerVC, animated: true, completion: nil)
        }))
        alertVC.addAction(UIAlertAction(title: "本地图片", style: .default, handler: { (_) in
            self.imagePickerVC.sourceType = .photoLibrary
            self.present(self.imagePickerVC, animated: true, completion: nil)
        }))
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        self.present(alertVC, animated: true, completion: nil)
    }
}
extension EditMaterialVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            dismiss(animated: true, completion: {
                if self.selectedRow.section == 2 {
                    let cell = self.tableView.cellForRow(at: self.selectedRow) as! ColorCell
                    cell.showAlert(image: image)
                } else if self.selectedRow.section == 4 {
                    let cell = self.tableView.cellForRow(at: self.selectedRow) as! OneImageCell
                    self.materialImage = image
                    self.tableView.beginUpdates()
                    cell.imgView.image = image
                    self.materialDetail.body = ""
                    self.tableView.endUpdates()
                } else if self.selectedRow.section == 5 {
                    let cell = self.tableView.cellForRow(at: self.selectedRow) as! ImageCell
                    cell.images.append(image)
                    cell.addImage()
                }
            })
        }
    }
}
extension EditMaterialVC: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        let point = textField.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        let index = (indexPath.section, indexPath.row)
        if index.0 == 1 {
            
        }
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        let point = textField.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        let index = (indexPath.section, indexPath.row)
        if index == (0, 0) {
            materialDetail.name = textField.text ?? ""
            editMaterial.name = textField.text
        } else if index == (0, 2) {
            materialDetail.no = textField.text ?? ""
            editMaterial.no = textField.text
        } else if index == (0, 3) {
            materialDetail.price = textField.text ?? ""
            editMaterial.price = Double(textField.text!)
        } else if index == (0, 4) {
            materialDetail.unit = textField.text ?? ""
            editMaterial.unit = textField.text
        } else {
            materialDetail.userDefine![index.1-1].value = textField.text ?? ""
            
        }
    }
}
extension EditMaterialVC: ColorCellDelegate {
    func insertColor(color: CodableColorOfMaterial) {
        materialDetail.color.append(color)
        var color = color
        color.type = 3
        editMaterial.color.append(color)
    }
    func deleteColor(at index: Int) {
        var color = materialDetail.color[index]
        var indexs = [Int]()
        if color.id == nil {
            for i in 0 ..< editMaterial.color.count {
                if editMaterial.color[i].type == 3 {
                    indexs.append(i)
                }
            }
            let atIndex = materialDetail.color.count - index
            editMaterial.color.remove(at: indexs[indexs.count-atIndex])
        } else {
            color.type = 1
            editMaterial.color.append(color)
        }
        materialDetail.color.remove(at: index)
    }
}
extension EditMaterialVC: ComponentCellDelegate {
    func insertComponent(component: CodableComponentOfMaterial) {
        materialDetail.component.append(component)
        var component = component
        component.type = 3
        editMaterial.component.append(component)
    }
    func deleteComponent(at index: Int) {
        var component = materialDetail.component[index]
        var indexs = [Int]()
        if component.id == nil {
            for i in 0 ..< editMaterial.component.count {
                if editMaterial.component[i].type == 3 {
                    indexs.append(i)
                }
            }
            let atIndex = materialDetail.component.count - index
            editMaterial.component.remove(at: indexs[indexs.count-atIndex])
        } else {
            component.type = 1
            editMaterial.component.append(component)
        }
        materialDetail.component.remove(at: index)
    }
}
extension EditMaterialVC: ImageCellDelegate {
    func insert(image: CodablePictureOfMaterial) {
        materialDetail.picture.append(image)
        var image = image
        image.type = 3
        editMaterial.picture.append(image)
    }
    func deleteImage(at index: Int) {
        var image = materialDetail.picture[index]
        var indexs = [Int]()
        if image.id == nil {
            for i in 0 ..< editMaterial.picture.count {
                if editMaterial.picture[i].type == 3 {
                    indexs.append(i)
                }
            }
            let atIndex = materialDetail.picture.count - index
            editMaterial.component.remove(at: indexs[indexs.count-atIndex])
        } else {
            image.type = 1
            editMaterial.picture.append(image)
        }
        materialDetail.picture.remove(at: index)
    }
}
